<template>
  <q-dialog v-model="show" persistent>
    <q-card class="card-body">
      <q-card-section>
        <div class="text-h6">添加歌曲</div>
      </q-card-section>

      <q-separator />

      <q-form
        @submit="isEdit ? editMusic() : createMusic()"
        class="q-gutter-md"
      >
        <q-card-section class="q-pt-none">
          <q-input
            dense
            v-model="music.name"
            label="歌曲名"
            autofocus
            @keyup.enter="show = false"
            :rules="[val => (val && val.length > 0) || '未输入歌曲名']"
            placeholder="例:夜曲"
          />

          <q-input
            dense
            v-model="music.description"
            type="textarea"
            label="简介"
            autofocus
            @keyup.enter="show = false"
            placeholder="例:这是一首好听的歌"
          />
        </q-card-section>

        <q-card-section>
          <uploader v-model:file="music.file" label="上传" />
        </q-card-section>

        <q-separator />

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn label="确认" type="submit" color="primary" />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { create, update } from '../../api/music/music';
import MyNotify from '../../utils/notify';
import uploader from '../../components/uploader.vue';

const props = defineProps({
  data: {
    type: Object,
    default() {
      return null;
    }
  }
});

const show = ref(true);
const isEdit = ref(Boolean(props.data));
// const file = ref(null);
const music = reactive(
  props.data || {
    name: '',
    description: '',
    file: null
  }
);

const emit = defineEmits(['createMusicSuccess', 'editMusicSuccess']);

const createMusic = () => {
  create(music).then(createdMusic => {
    show.value = false;
    emit('createMusicSuccess');
    MyNotify.success(`音乐《${createdMusic.name}》创建成功`);
  });
};
const editMusic = () => {
  update(music.id, music).then(updatedMusic => {
    show.value = false;
    emit('editMusicSuccess');
    MyNotify.success(`音乐《${updatedMusic.name}》编辑成功`);
  });
};
</script>

<style scoped>
.card-body {
  /* min-width: 500px; */
  padding: 20px 10px;
}
</style>
